﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PureMVC.Interfaces;
using PureMVC.Patterns;
using SMS.Core.Model;
using SMS.Core.View;
using SMS.Core.View.Component;
using SMS.Core.Model.Util;
using System.Reflection;
using System.Threading;

namespace SMS.Core.Controller.Commands
{
    class MainStartupCommand : SimpleCommand, ICommand
    {
        #region ICommand Members

        public override void Execute(INotification notification)
        {
            var m_loginMediator = Facade.RetrieveMediator(StartupMediator.NAME);
            LoginForm m_loginForm = (LoginForm)m_loginMediator.ViewComponent;
            // Clean up the login form and any mediators/proxies/commands associated with it.
            m_loginForm.CustomComponent.Dispose();
            Facade.RemoveMediator(LoginMediator.NAME);
            Facade.RemoveProxy(LoginProxy.NAME);
            
            // Use reflection to remove all notification/command pairs in application constants.
            foreach (FieldInfo fi in ClassConstantEnumerator.GetConstants(typeof(ApplicationConstants)))
                try { Facade.RemoveCommand(fi.Name); }
                catch { /*Ignore*/ } // HACK: Ignoring reflection exceptions
            // Also remove notification/command pairs in model constants
            foreach (FieldInfo fi in ClassConstantEnumerator.GetConstants(typeof(ModelConstants.UserAccount)))
                try { Facade.RemoveCommand(fi.Name); }
                catch { /* Ignore*/ }

            // Close the login form.
            var owner = m_loginForm.Owner;
            m_loginForm.Close();
            m_loginForm.Dispose();
        }

        #endregion
    }
}
